import React, { Component } from 'react';
import { SearchBar, Button} from 'antd-mobile';
import Topnav from '@/components/Topnav'
import { SearchBox } from './style'
import {SearchApi} from '../../api/searchApi'
import store from '@/utils/store'
class Index extends Component {
    state = {
        selectRet:[],
        historyRet:store.get('search') === "" ? [] : store.get('search')
    }
    searchFun = async value => {
        let ret = await SearchApi(value)
        this.state.selectRet = ret.data
        this.setState({},() => {
            let histories = store.get('search') === "" ? [] : store.get('search')
            if(!histories.includes(value)){
                histories.unshift(value)
                histories = histories.slice(0,3)
                store.set('search',histories)
                this.setState({ historyRet:histories })
            }
        })
        
    }
    render() {
        return (
            <SearchBox>
                 <Topnav title="搜索页面" leftText="返回" onLeft={ () =>this.props.history.replace('/home')  } />
                 <SearchBar 
                    placeholder="输入想搜索的菜系" 
                    onSubmit={ evl => this.searchFun(evl) }
                    onClear = { () => this.setState({ selectRet:[] }) }
                    ref={ref => this.kw = ref}
                />
                {
                     this.state.historyRet.map(item => (
                        <span 
                            key={item.index} 
                            style={{ width:'auto',display:'inline-block',border:"solid 0.01px black",textAlign:'center',padding:'0 0.1rem'  }}
                            onClick={ () => this.kw.setState({ value:item }) }
                        >{item}</span>
                        
                    ))
                }
                <ul>
                { 
                    this.state.selectRet.map(item => (
                        <li key={item.id}>{item.name}</li>
                    ))
                }
                </ul>
                
            </SearchBox>
        );
    }
}

export default Index;
